package com.whu.util;


import java.util.Calendar;

/**
 * @Description:BCD码转换工具类，8421标准
 * @Author chengeng
 * @Date 2021/10/18 17:33
 **/
public class BCDUtil {

    public static byte[] calendar2BCD(Calendar calendar){
        byte[] bcd = new byte[5];
        bcd[0] = (byte) (calendar.get(Calendar.MONTH)+1);// 得到的月份比实际月份小1
        bcd[1] = (byte)calendar.get(Calendar.DAY_OF_MONTH);
        bcd[2] = (byte)calendar.get(Calendar.HOUR_OF_DAY);
        bcd[3] = (byte)calendar.get(Calendar.MINUTE);
        bcd[4] = (byte)calendar.get(Calendar.SECOND);
        return bcd;
    }
    public static String bcdTime2String(byte[] bcd){
        String res = formatTimeStr(Byte.toString(bcd[0]))+"."+formatTimeStr(Byte.toString(bcd[1]))+" "
                +formatTimeStr(Byte.toString(bcd[2]))+":"+formatTimeStr(Byte.toString(bcd[3]))+":"
                +formatTimeStr(Byte.toString(bcd[4]));
        return res;
    }
    public static String formatTimeStr(String timeStr){
        if(timeStr.length()==1){
            timeStr = '0'+timeStr;
        }
        return timeStr;
    }

    //long->BCD
    /**
     * @Description:将Long型的时间戳转化为32位BCD码
     * @Param [timeStamp]
     * @return int
     * @Author chengeng
     * @Date 2021/10/16 17:44
     **/
    public static int long2BCD(Long timeStamp){
        String str = String.valueOf(timeStamp);
        String b_num="";
        int res=0;
        for (int i = 0; i < str.length(); i++) {
            String b = Integer.toBinaryString(Integer.parseInt(str.valueOf(str.charAt(i))));
            int b_len=4-b.length();
            for(int j=0;j<b_len;j++){
                b="0"+b;
            }
            b_num+=b;
        }
        res=Integer.parseInt(b_num,2);
        return res;
    }
    //BCD->long
    /**
     * @Description将32位BCD码转化为long型时间戳
     * @Param [bcd]
     * @return long
     * @Author chengeng
     * @Date 2021/10/18 17:32
     **/
    public static long bcd2Long(int bcd) {
        byte[] bytes = ByteUtil.getBytes(bcd);
        StringBuffer temp = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
            temp.append((byte) (bytes[i] & 0x0f));
        }
        return Long.parseLong(temp.toString());
    }

}
